import axios from "axios";
import router from "../../router/router";
import { ElLoading } from "element-plus";
import emitter from "@/utils/bus";
let loadingRequestCount = 0;
let loadingInstance: any;
// 加载弹出loading
const showLoading = () => {
  if (loadingRequestCount === 0) {
    loadingInstance = ElLoading.service({ target: "#app" });
  }
  loadingRequestCount += 1;
};
// 隐藏loading
const hideLoading = () => {
  if (loadingRequestCount <= 0) return;
  loadingRequestCount -= 1;
  if (loadingRequestCount === 0) {
    loadingInstance.close();
  }
};
axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers["token"] = localStorage.token || "";
axios.defaults.headers.post["Content-Type"] = "application/json";
const api = axios.create({
  timeout: 3000,
});
// 请求白名单
const whiteList = <any>["/api/login/qr/check", "/api/cloudsearch"];
api.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem("token") || "";
    if (token && token !== "") {
      if (config && config.headers) {
        config.headers.token = token;
      }
    }
    // if (whiteList.indexOf(config.url) === -1) {
    //   showLoading();
    // }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
api.interceptors.response.use(
  (response) => {
    hideLoading();
    return response;
  },
  (err) => {
    if (err.request.status === 301) {
      // emitter.emit("loginState", true);
    }
    // hideLoading();
    return Promise.reject(err);
  }
);
export default api;
